package com.sdkx.wear_os.utils


import android.view.View
import android.widget.RadioGroup
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter4.BaseQuickAdapter
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * 防止重复点击事件 默认0.5秒内不可重复点击
 * @param interval 时间间隔 默认0.5秒
 * @param action 执行方法
 */
var lastClickTime = 0L
fun View.clickNoRepeat(interval: Long = 500, action: (view: View) -> Unit) {
    setOnClickListener {
        val currentTime = System.currentTimeMillis()
        if (lastClickTime != 0L && (currentTime - lastClickTime < interval)) {
            return@setOnClickListener
        }
        lastClickTime = currentTime
        action(it)
    }
}

/**
 * 防止重复点击事件 默认0.5秒内不可重复点击
 * @param interval 时间间隔 默认0.5秒
 * @param action 执行方法
 */
var lastItemClickTime = 0L
fun <T : Any, VH : RecyclerView.ViewHolder> BaseQuickAdapter<T, VH>.itemClickNoRepeat(
    interval: Long = 500,
    action: (view: View, position: Int) -> Unit
) {
    setOnItemClickListener { _, view, position ->
        val currentTime = System.currentTimeMillis()
        if (lastItemClickTime != 0L && (currentTime - lastItemClickTime < interval)) {
            return@setOnItemClickListener
        }
        lastItemClickTime = currentTime
        action(view, position)
    }
}

/**
 * 防止重复点击事件 默认0.5秒内不可重复点击
 * @param interval 时间间隔 默认0.5秒
 * @param action 执行方法
 */
var lastItemChildClickTime = 0L
fun <T : Any, VH : RecyclerView.ViewHolder> BaseQuickAdapter<T, VH>.itemChildClickNoRepeat(
    interval: Long = 500,
    id: Int,
    action: (view: View, position: Int) -> Unit
) {
    addOnItemChildClickListener(id) { _, view, position ->
        val currentTime = System.currentTimeMillis()
        if (lastItemChildClickTime != 0L && (currentTime - lastItemChildClickTime < interval)) {
            return@addOnItemChildClickListener
        }
        lastItemChildClickTime = currentTime
        action(view, position)
    }
}

/**
 * 防止重复点击事件 默认0.5秒内不可重复点击
 * @param interval 时间间隔 默认0.5秒
 * @param action 执行方法
 */
var lastCheckedTime = 0L
fun RadioGroup.checkedChange(interval: Long = 1000, action: (view: View, checkedId: Int) -> Unit) {
    setOnCheckedChangeListener { group, checkedId ->
        val currentTime = System.currentTimeMillis()
        if (lastCheckedTime != 0L && (currentTime - lastCheckedTime < interval)) {
            return@setOnCheckedChangeListener
        }
        lastCheckedTime = currentTime
        action(group, checkedId)
    }
}

// 防止重复点击事件
fun listener(view: View, click: (Boolean) -> Unit) {
    view.setOnClickListener {
        view.isEnabled = false
        click(true)
        MainScope().launch {
            delay(3000)
            view.isEnabled = true
            click(false)
        }
    }
}